<template>
  <pageTabelLayout>
    <template #pageHeader>
      <div class="search-form isheader" v-if="headerShow">
        <div>
          <a-form size="small" :model="pageData" layout="inline">
            <CorporateSectorCascader
              :configCascader="configCascader2"
              @changeCascader="changeCascader2"
            />
            <a-form-item label="仓库">
              <a-select
                popup-container="html"
                class="bacClass"
                :style="{ width: '200px' }"
                v-model="pageData.b"
                allow-clear
              >
                <a-option v-for="item in fhWhList" :value="item.id">
                  {{ item.warehouseName }}
                </a-option>
              </a-select>
            </a-form-item>
            <a-form-item label="物料编号">
              <a-input
                allow-clear
                :style="{ width: '200px' }"
                class="bacClass"
                v-model="pageData.c"
              />
            </a-form-item>
            <a-form-item label="物料名称">
              <a-input
                allow-clear
                :style="{ width: '200px' }"
                class="bacClass"
                v-model="pageData.d"
              />
            </a-form-item>
          </a-form>
        </div>
        <div>
          <Toolbar
            :items="[`${permissionStore.hasPermisson('wjckc.cx') ? '查询' : ''}`, '导出']"
            @select="selectHandler"
            @export="exportExcel"
          >
          </Toolbar>
        </div>
      </div>
      <div class="my-divisders">
        <a-divider orientation="center">
          <icon-double-up
            v-if="headerShow"
            @click="headerShow = false"
            :strokeWidth="2"
            :size="18"
          />
          <icon-double-down v-else @click="headerShow = true" :strokeWidth="2" :size="18" />
        </a-divider>
      </div>
      <div class="gang"></div>
    </template>
    <template #pageTabel>
      <a-tabs :lazy-load="true" :justify="true">
        <a-tab-pane title="五金仓库存查询" :key="1">
          <AgGridVuesCopys
            :rowHeight="33"
            :headerHeight="33"
            :suppressCopyRowsToClipboard="true"
            :suppressDragLeaveHidesColumns="true"
            rowSelection="multiple"
            @grid-ready="gridReady"
            @columnResized="onColumnResized"
            @columnMoved="onColumnMoved"
            @rowClicked="onRowClicked"
            @columnVisible="onColumnVisible"
            style="height: calc(100% - 45px)"
            :defaultColDef="defaultColDef"
            class="ag-theme-alpine"
            :rowData="tableDataList"
            :columnDefs="tc"
            :localeText="localeText1"
          >
          </AgGridVuesCopys>
          <paginationCopys
            :page-size-options="pagingList1"
            :total="fySelet2.total"
            show-total
            show-jumper
            show-page-size
            @change="PageSize2"
            @page-size-change="change2"
            style="justify-content: center"
            :page-size="fySelet2.size"
            :current="fySelet2.page"
          />
        </a-tab-pane>
      </a-tabs>
    </template>
    <a-drawer
      cancel-text="关闭"
      :drawer-style="{ zIndex: 9999 }"
      height="91vh"
      placement="bottom"
      :visible="pageData1.showAdd1"
      unmountOnClose
      @cancel="pageData1.showAdd1 = false"
    >
      <template #title> 选择编号 </template>
      <div :style="{ height: '100%', padding: '10px' }" style="background: #fff">
        <encapsulation-agrid
          ref="refgridOption1"
          :configaggrid="configaggrid1"
        ></encapsulation-agrid>
      </div>
    </a-drawer>
  </pageTabelLayout>
</template>
<script setup lang="ts">
  import { ref, reactive } from 'vue'
  import { post, get } from '@/api/http'
  import { localeText } from '@/api/aggridZw'
  
  import Toolbar from '@/components/Toolbar.vue'
  import { Message, Modal } from '@arco-design/web-vue'
  import { exportJsonToExcel } from '@/api/Export2Excel'
  import { exportStyleExcel } from '@/api/Export2StyleExcel'
  import WHService from '@/service/wh'
  import CorporateSectorCascader from '@/components/corporateSectorCascader/inde.vue'
  import usePermission from '@/store/modules/permission'
  import { pagingList } from '@/api/paging'
  import { saveOrUpdateGridState as saveOrUpdateGridState01 } from '@/hooks/useGridState'
  import { log } from 'echarts/types/src/util/log'
  import { tc2 } from '@/views/DyeingFactoryPartsCost/RanChangJianZi'
  import { template } from 'lodash'
  import { tableColumns1 } from './OrderDeliveryList2'
  import setTableTotalRow from '@/utils/setTableTotalRow.ts'
  const pageData1: any = reactive({
    a: '',
    b: '',
    c: '',
    d: '',
    e: '',
    f: '',
    g: '',
    z: '',
    dropDownTime: {},
    showAdd_DY: false,
    dataList: [],
    isEdit: false,
    showAdd1: false,
    CheckNumberList: {},
    bigName: [],
    samllName: [],
    codeList: [],
    specList: [],
    wlNameList: [],
  })
  const gridOption = ref()
  const colState = ref()
  const gridReady = (params: any) => {
    gridOption.value = params.api
    colState.value = params.columnApi
  }
  let configaggrid1: any = ref({
    url: 'wms/ironwareStockInfo/getListByOut', //接口路径
    queryData: {
      materialCode: '',
      warehouseId: '',
    },
    paginationShow: false, //分页是否显示
    invokeiIterface: true, //是否调用接口
    rowMultiSelectWithClick: true, //点击行是否多选
    column: tableColumns1,
  })
  const onRowClicked = () => {
    configaggrid1.value.queryData.materialCode = gridOption.value.getSelectedRows()[0].materialCode
    configaggrid1.value.queryData.warehouseId = gridOption.value.getSelectedRows()[0].warehouseId
  }
  const pagingList1: any = ref(pagingList)
  const permissionStore = usePermission()
  const headerShow = ref(true)
  const localeText1: any = ref(localeText)

  const pageData: any = reactive({
    a: '',
    b: '',
    c: '',
    d: '',
  })

  const selectHandler = () => {
    fySelet2.page = 1
    wjYcList()
  }
  const tableDataList: any = ref([])

  const defaultColDef = {
    sortable: true,
    resizable: true,
    filter: true,
  }

  const fySelet2: any = reactive({
    total: 10,
    size: 10,
    page: 1,
  })

  const PageSize2 = (val: any) => {
    fySelet2.page = val
    wjYcList()
  }

  const change2 = (val: any) => {
    fySelet2.size = val
    wjYcList()
  }

  const tc = [
    {
      showRowGroup: 'hide_def',
      headerName: 'ID',
      checkboxSelection: true,
      headerCheckboxSelection: true,
      pinned: 'left',
      width: 50,
      resizable: false,
      filter: false,
      sortable: false,
      minWidth: 50,
      maxWidth: 50,
      lockPosition: 'left',
    },
    {
      headerName: '公司',
      field: 'companyName',
      // pinned: o['fixed'],
      width: 150,
    },
    // {
    //     headerName: '仓库类型名称111',
    //     field: 'warehouseTypeName',
    //     width: 150
    // },
    {
      headerName: '仓库名称',
      field: 'warehouseName',
      width: 150,
    },
    {
      headerName: '物料大类',
      field: 'majorCategory',
      width: 150,
    },
    {
      headerName: '物料中类',
      field: 'middleCategory',
      width: 150,
    },
    {
      headerName: '物料小类',
      field: 'subCategory',
      width: 150,
    },
    {
      headerName: '物料编号',
      field: 'materialCode',
      width: 150,
    },
    {
      headerName: '物料名称',
      field: 'materialName',
      width: 150,
    },
    {
      headerName: '数量',
      field: 'totalNum',
      width: 150,
    },
    // {
    //     headerName: '单位',
    //     field: 'unit',
    //     width: 150
    // },
    {
      headerName: '规格',
      field: 'specification',
      width: 150,
    },
    {
      headerName: '单价',
      field: 'price',
      width: 150,
    },
    {
      headerName: '等级',
      field: 'grade',
      width: 150,
    },
    {
      headerName: '单位',
      field: 'unit',
      width: 150,
    },
    {
      headerName: '操作',
      field: 'fixAssetStatus',
      pinned: 'right',
      width: 150,
      cellRenderer: {
        template: `<a-tag v-if="a==1" color="#165dff" @click="goDetail">固资详情</a-tag>`,
        setup(params: any) {
          const goDetail = () => {
            pageData1.showAdd1 = true
          }
          return {
            goDetail,
            a: params.params.data.fixAssetStatus,
          }
        },
      },
      cellStyle: (params: any) => {
        if (params.node.rowPinned == 'bottom') return { display: 'none' }
      },
    },
  ]
  const wjYcList = () => {
    post({
      url: 'wms/ironwareStockSummary/getPage',
      data: {
        page: fySelet2.page,
        size: fySelet2.size,
        materialCode: pageData.c,
        materialName: pageData.d,
        companyId: pageData.a,
        warehouseId: pageData.b,
      },
    }).then((res: any) => {
      gridOption.value.setRowData(res.data.data)
      setTableTotalRow(gridOption, res.data.data, ['totalNum'])
      tableDataList.value = res.data.data
      fySelet2.total = res.data.total
    })
  }
  const configCascader2 = ref<{}>({
    corporateWidth: '180px', //公司宽度
    sectorWidth: '180px', //部门宽度
    corporateRquired: false, //公司是否必填
    sectorRquired: false, //部门是否必填
    size: 'mini', //选择框大小'mini' | 'small' | 'medium' | 'large'
    corporateName: '选择公司', //公司label
    sectorName: '选择部门', //部门label
    cascaderShow: 'sector', //配置部门不显示
  })
  const whService = new WHService()
  const fhWhList: any = whService.whList
  const changeCascader2 = (data: any) => {
    const { corporateId, sectorId, sectorLabel, corporateLabel } = data
    pageData.b = ''
    pageData.a = corporateId
    whService.getWarhouseListByFirmId(corporateId, '五金仓')
  }
  onMounted(() => {
    wjYcList()
    updateGridState01()
  })

  /**
   * 导出EXCEL
   */
  const exportExcel = () => {
    //const header = ['公司', '仓库类型名称', '仓库名称', '物料大类', '物料小类','物料编号', '物料名称', '数量', '单位','规格', '单价', '等级']
    //const filterVal = ['companyName', 'warehouseTypeName', 'warehouseName', 'majorCategory', 'subCategory','materialCode', 'materialName', 'totalNum', 'unit', 'specification', 'price','grade']
    let header = tc
      .map((o) => {
        return o.headerName
      })
      .splice(1)
    let filterCols = tc
      .map((c) => {
        return c.field
      })
      .splice(1)
    let data = formatJson(filterCols, tableDataList.value)
    console.log(data)
    exportStyleExcel({ header, data, filename: '五金仓库存表.xlsx' })
  }

  /**
   * 过滤需要导出的列，并转换数据格式，如STATUS
   */
  const formatJson = (filterVal: any, jsonData: any) => {
    return jsonData.map((v: any) =>
      filterVal.map((j: any) => {
        if (v[j] == null) {
          console.log(j)
          console.log(v[j])
          return ''
        }
        if (j == 'status') {
          if (v[j] == 1) {
            return '正常'
          } else {
            return '禁用'
          }
        } else {
          if (j) {
            return v[j]
          }
        }
      })
    )
  }
  const { saveGridState: saveGridState01, updateGridState: updateGridState01 } =
    saveOrUpdateGridState01('NventoryManagement2-1', gridOption, colState, tc)
  const onColumnMoved = () => {
    saveGridState01()
  }
  const onColumnResized = () => {
    saveGridState01()
  }
  const onColumnVisible = () => {
    saveGridState01()
  }
</script>
